package com.iflytek.uoamp.agent.core.agentclient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.uoamp.agent.common.constants.CommonConstants;
import com.iflytek.uoamp.agent.core.AgentCoreMain;
import com.iflytek.uoamp.agent.core.agentclient.sync.SyncWriteFuture;
import com.iflytek.uoamp.agent.core.agentclient.sync.SyncWriteMap;
import com.iflytek.uoamp.agent.core.conf.AgentCoreConfig;
import com.iflytek.uoamp.agent.core.sender.obj.MsgType;
import com.iflytek.uoamp.agent.core.sender.obj.RequestData;
import com.iflytek.uoamp.agent.core.sender.obj.ResponseData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: AgentClientHandler
 * @Description: netty客户端具体业务处理类
 * @author qinanyuan
 * @date 2017年3月22日 下午9:08:47
 */
public class AgentClientHandler extends SimpleChannelInboundHandler<byte[]> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
		ResponseData responseData = JSONObject.parseObject(new String(msg, "utf-8"), ResponseData.class);
		String requestId = responseData.getRandomId();
		SyncWriteFuture future = (SyncWriteFuture) SyncWriteMap.syncKey.get(requestId);
		if (future != null) {
			future.setResponse(responseData);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Logger.getRootLogger().info("--- Server is active ---");
//		RequestData request = new RequestData();
//		request.setMsgType(MsgType.AUTH);
//		request.setRequestInfo("netty Ping test!");
//		Logger.getRootLogger().info("注册本机clentId!" + JSON.toJSONString(request));
//		ctx.writeAndFlush((JSON.toJSONString(request)).getBytes());
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) {
		Logger.getRootLogger().info("--- Server is inactive ---");
		new Thread(new Runnable() {
			boolean isconnect = false;
			int i = 0;
			@Override
			public void run() {
				while (!isconnect) {
					// 10s 之后尝试重新连接服务器
					Logger.getRootLogger().info("10s 之后尝试重新连接服务器...");
					try {
                        TimeUnit.SECONDS.sleep(CommonConstants.CONNECT_INTERVAL);
						isconnect = AgentClient.getInstance().doConnect(AgentCoreConfig.getInstance().getHost(), AgentCoreConfig.getInstance().getPort());
						i++;
						Logger.getRootLogger().info("第" + i + "次断线重连，结果为：" + isconnect);
					} catch (InterruptedException e) {
						Logger.getRootLogger().error("断线重连错误：" + e.toString());
					}
				}
                AgentCoreMain.confirmClientId();
			}
		}).start();
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			// 不管是读事件空闲还是写事件空闲都向服务器发送心跳包
			sendHeartBeat(ctx);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//		Logger.getRootLogger().info("连接出现异常:" + cause);
	}

	/**
	 * 发送心跳包
	 *
	 * @param ctx
	 */
	private void sendHeartBeat(ChannelHandlerContext ctx) {
		RequestData request = new RequestData();
		request.setMsgType(MsgType.HEARTBEAT);
		request.setRequestInfo("send heartBeat msg!");
		ctx.writeAndFlush(JSON.toJSONString(request).getBytes());
	}

}
